﻿using System;
using System.Collections.Generic;

using System.Text;
using AhpilyServer;
using Island;

namespace Server
{
    /// <summary>
    /// 用户管理器
    /// </summary>
    public class AccountCache : Singleton<AccountCache>
    {
        private List<ClientPeer> actors = new List<ClientPeer>();
        private Dictionary<string, Account> accDic = new Dictionary<string, Account>();
        private Dictionary<string, ClientPeer> peerDic = new Dictionary<string, ClientPeer>();

        /// <summary>
        /// 添加用户,用户上线
        /// </summary>
        /// <param name="username"></param>
        /// <param name="client"></param>
        public void AddActor(PBAccount acc, ClientPeer client)
        {
            client.id = acc.id;

            accDic.Add(acc.id, Account.FromPB(acc));
            peerDic.Add(acc.id, client);
            actors.Add(client);

            Console.WriteLine("用户[" + acc.id + "]上线了");
        }

        /// <summary>
        /// 删除用户，用户下线
        /// </summary>
        /// <param name="username"></param>
        public void DelActor(ClientPeer client)
        {
            accDic.Remove(client.id);
            peerDic.Remove(client.id);
            actors.Remove(client);
            Console.WriteLine("用户[" + client.id + "]下线了");
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public ClientPeer GetActor(string id)
        {
            ClientPeer peer;
            if(peerDic.TryGetValue(id,out peer))
            {
                return peer;
            }
            return null;
        }

        public Account GetAccount(string id)
        {
            Account acc;
            if (accDic.TryGetValue(id, out acc))
            {
                return acc;
            }
            return null;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public List<ClientPeer> GetAllActors()
        {
            return actors;
        }
    }
}
